<?php

namespace App\Models\Traits;

use App\User;
use Illuminate\Support\Facades\Auth;

trait Favorite
{
    public function favorites()
    {
        return $this->morphToMany(User::class, 'favorite', 'favorite')->withTimestamps();

    }

//切换收藏
    public function favorite()
    {
        $method = $this->isfavorite ? 'detach' : 'attach';
        //防止没登陆时获取Auth::id得错误
        if (Auth::check()) {
            if (user('id') == $this->user_id) {
                return back()->with('danger','不可以收藏自己');
            }
            $this->favorites()->$method([Auth::id()], [
                'site_id' => site()['id'],
                'module_id' => module()['id']
            ]);
        }
        $this->favorite_count = $this->favorites()->count();
        $this->save();
    }

    public function getIsFavoriteAttribute()
    {
        //通过中间表wherePivot筛选当前user_id用户是否存在，即是否搜藏了该视频或贴子
        return $this->favorites()->wherePivot('user_id', user('id'))->exists();
    }
}
